<!-- 表格列表组件 -->
<script setup lang="ts">
import { message } from 'ant-design-vue';
import type { TableRowSelection } from 'ant-design-vue/es/table/interface';
import { computed, ref, watch } from 'vue';
import type { GeneralTableProps } from '../index';

const props = withDefaults(defineProps<GeneralTableProps>(), {
  columns: () => [],
  data: () => [],
  loading: false,
  pagination: () => ({
    current: 1,
    pageSize: 10,
    total: 0
  }),
  enableSelection: true,
  selectedRowKeys: () => []
});

const emits = defineEmits(['change', 'selectionChange', 'exportData']);

// 内部管理的选中行keys
const internalSelectedRowKeys = ref<(string | number)[]>([]);

// 监听外部传入的selectedRowKeys变化
watch(
  () => props.selectedRowKeys,
  newKeys => {
    if (newKeys) {
      internalSelectedRowKeys.value = [...newKeys];
    }
  },
  { immediate: true }
);

// 行选择配置
const rowSelectionConfig = computed<TableRowSelection<any> | undefined>(() => {
  if (!props.enableSelection) return undefined;

  return {
    type: 'checkbox',
    selectedRowKeys: internalSelectedRowKeys.value,
    onChange: (selectedRowKeys: (string | number)[], selectedRows: any[]) => {
      internalSelectedRowKeys.value = selectedRowKeys;
      emits('selectionChange', selectedRowKeys, selectedRows);
    },
    onSelectAll: (selected: boolean, selectedRows: any[], changeRows: any[]) => {
      const keys = selected ? props.data.map(item => item.id || item.key) : [];
      internalSelectedRowKeys.value = keys;
      emits('selectionChange', keys, selected ? props.data : []);
    }
  };
});

// 是否有选中数据
const hasSelectedData = computed(() => {
  return internalSelectedRowKeys.value.length > 0;
});

// 导出数据
const handleExportData = () => {
  if (!hasSelectedData.value) {
    message.warning('请先选择要导出的数据');
    return;
  }

  const selectedData = props.data.filter(item => internalSelectedRowKeys.value.includes(item.id || item.key));

  emits('exportData', selectedData);
};

// 暴露方法给父组件使用
defineExpose({
  handleExportData,
  hasSelectedData,
  selectedRowKeys: internalSelectedRowKeys,
  selectedData: computed(() => props.data.filter(item => internalSelectedRowKeys.value.includes(item.id || item.key)))
});

const handleTableChange = (pagination: any, filters: any, sorter: any) => {
  emits('change', pagination, filters, sorter);
};
</script>

<template>
  <div class="w-full rounded bg-white p-4">
    <!-- 表格 -->
    <ATable
      :columns="props.columns"
      :data-source="props.data"
      :loading="props.loading"
      :pagination="false"
      :row-selection="rowSelectionConfig"
      :row-key="record => record.id || record.key"
      size="small"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, index }">
        <slot name="bodyCell" :column="column" :record="record" :index="index"></slot>
      </template>
    </ATable>
  </div>
</template>

<style scoped lang="scss"></style>
